"""
现有配置迁移工具
"""
import os
import re
import yaml
from pathlib import Path
from typing import Dict, Any, Optional

class ConfigMigrator:
    """配置迁移器"""
    
    def __init__(self, project_root: Optional[Path] = None):
        self.project_root = project_root or Path(__file__).parent.parent.parent
        self.output_dir = self.project_root / "config" / "unified"
        self.output_dir.mkdir(parents=True, exist_ok=True)
    
    def migrate_all(self):
        """迁移所有现有配置"""
        print("🔄 开始迁移现有配置...")
        
        # 1. 分析现有配置
        existing_configs = self._analyze_existing_configs()
        print(f"📊 发现 {len(existing_configs)} 个配置源")
        
        # 2. 生成统一配置
        unified_config = self._generate_unified_config(existing_configs)
        
        # 3. 写入配置文件
        self._write_config_files(unified_config)
        
        # 4. 生成迁移报告
        self._generate_migration_report(existing_configs, unified_config)
        
        print("✅ 配置迁移完成!")
    
    def _analyze_existing_configs(self) -> Dict[str, Any]:
        """分析现有配置文件"""
        configs = {}
        
        print("🔍 分析现有配置文件...")
        
        # 分析环境配置
        env_file = self.project_root / "config" / "environment.env"
        if env_file.exists():
            configs['environment'] = self._parse_env_file(env_file)
            print(f"  ✓ 发现环境配置: {env_file}")
        
        # 分析数据库环境配置
        db_env_file = self.project_root / "databases" / "configs" / "environments" / "redfire.env"
        if db_env_file.exists():
            configs['database_env'] = self._parse_env_file(db_env_file)
            print(f"  ✓ 发现数据库配置: {db_env_file}")
        
        # 分析共享服务配置
        service_config = self.project_root / "shared" / "core" / "config" / "backend" / "service_config.py"
        if service_config.exists():
            configs['service_config'] = self._analyze_service_config_file(service_config)
            print(f"  ✓ 发现服务配置: {service_config}")
        
        return configs
    
    def _parse_env_file(self, env_file: Path) -> Dict[str, str]:
        """解析环境变量文件"""
        env_vars = {}
        
        if not env_file.exists():
            return env_vars
        
        with open(env_file, 'r', encoding='utf-8') as f:
            for line in f:
                line = line.strip()
                if line and not line.startswith('#') and '=' in line:
                    key, value = line.split('=', 1)
                    env_vars[key.strip()] = value.strip().strip('"\'')
        
        return env_vars
    
    def _analyze_service_config_file(self, config_file: Path) -> Dict[str, Any]:
        """分析Python服务配置文件"""
        config_info = {}
        
        if not config_file.exists():
            return config_info
        
        with open(config_file, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 提取端口配置
        port_patterns = [
            r'(\w+_port):\s*int\s*=\s*Field\(default=(\d+)',
            r'(\w+_PORT)\s*=\s*(\d+)',
        ]
        
        ports = {}
        for pattern in port_patterns:
            matches = re.findall(pattern, content)
            for var_name, port_value in matches:
                ports[var_name] = int(port_value)
        
        config_info['ports'] = ports
        
        # 提取主机配置
        host_patterns = [
            r'service_host:\s*str\s*=\s*Field\(default="([^"]+)"',
            r'api_host:\s*str\s*=\s*Field\(default="([^"]+)"',
        ]
        
        hosts = {}
        for pattern in host_patterns:
            matches = re.findall(pattern, content)
            for match in matches:
                if 'service_host' in pattern:
                    hosts['service_host'] = match
                elif 'api_host' in pattern:
                    hosts['api_host'] = match
        
        config_info['hosts'] = hosts
        
        return config_info
    
    def _generate_unified_config(self, existing_configs: Dict[str, Any]) -> Dict[str, Any]:
        """生成统一配置"""
        print("🏗️  生成统一配置...")
        
        # 基础配置模板
        unified = {
            "version": "2.0",
            "config_schema": "redfire-unified-v2",
            "global": {
                "project_name": "RedFire Trading Platform",
                "version": "2.0.0",
                "debug": False,
                "timezone": "Asia/Shanghai",
                "encoding": "utf-8"
            },
            "services": {},
            "databases": {},
            "cache": {},
            "security": {},
            "logging": {},
            "monitoring": {},
            "external_services": {}
        }
        
        # 合并服务端口配置
        self._merge_service_ports(unified, existing_configs)
        
        # 合并数据库配置
        self._merge_database_config(unified, existing_configs)
        
        # 合并缓存配置
        self._merge_cache_config(unified, existing_configs)
        
        # 合并安全配置
        self._merge_security_config(unified, existing_configs)
        
        # 添加日志配置
        unified['logging'] = {
            "level": "INFO",
            "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
            "handlers": [
                {"type": "console"},
                {
                    "type": "file",
                    "filename": "logs/redfire.log",
                    "max_bytes": 10485760,
                    "backup_count": 5
                }
            ]
        }
        
        # 添加监控配置
        unified['monitoring'] = {
            "enabled": True,
            "metrics_port": 9090,
            "health_check_interval": 30,
            "prometheus": {
                "enabled": True,
                "endpoint": "/metrics"
            }
        }
        
        return unified
    
    def _merge_service_ports(self, unified: Dict[str, Any], existing: Dict[str, Any]):
        """合并服务端口配置"""
        # 从环境配置提取端口
        env_config = existing.get('environment', {})
        service_config = existing.get('service_config', {})
        
        # 定义服务映射
        service_mappings = {
            "api_gateway": {
                "name": "API Gateway",
                "port": self._get_port_from_configs(['REDFIRE_API_GATEWAY_PORT'], env_config, service_config, 8000),
                "enabled": True
            },
            "user_service": {
                "name": "User Service", 
                "port": self._get_port_from_configs(['REDFIRE_USER_SERVICE_PORT', 'user_trading_port'], env_config, service_config, 8001),
                "enabled": True
            },
            "market_data_service": {
                "name": "Market Data Service",
                "port": self._get_port_from_configs(['REDFIRE_MARKET_DATA_SERVICE_PORT', 'strategy_data_port'], env_config, service_config, 8002),
                "enabled": True
            },
            "trading_service": {
                "name": "Trading Service",
                "port": 8003,
                "enabled": False
            },
            "notification_service": {
                "name": "Notification Service",
                "port": self._get_port_from_configs(['monitor_port'], env_config, service_config, 8004),
                "enabled": False
            }
        }
        
        # 生成服务配置
        for service_key, service_info in service_mappings.items():
            unified['services'][service_key] = {
                "name": service_info['name'],
                "port": service_info['port'],
                "host": "0.0.0.0",
                "enabled": service_info['enabled'],
                "health_check": f"/api/v1/{service_key.replace('_', '-')}/health",
                "docs_url": "/docs",
                "timeout": 30
            }
    
    def _get_port_from_configs(self, port_keys: list, env_config: Dict, service_config: Dict, default: int) -> int:
        """从多个配置源获取端口"""
        # 优先级: 环境变量 > 服务配置 > 默认值
        
        # 检查环境变量
        for key in port_keys:
            if key in env_config:
                try:
                    return int(env_config[key])
                except ValueError:
                    continue
        
        # 检查服务配置
        service_ports = service_config.get('ports', {})
        for key in port_keys:
            if key in service_ports:
                return service_ports[key]
        
        return default
    
    def _merge_database_config(self, unified: Dict[str, Any], existing: Dict[str, Any]):
        """合并数据库配置"""
        db_env = existing.get('database_env', {})
        env_config = existing.get('environment', {})
        
        # MySQL主数据库配置
        unified['databases']['primary'] = {
            "type": "mysql",
            "host": db_env.get('REDFIRE_MYSQL_HOST', env_config.get('REDFIRE_MYSQL_HOST', 'localhost')),
            "port": int(db_env.get('REDFIRE_MYSQL_PORT', env_config.get('REDFIRE_MYSQL_PORT', '3307'))),
            "database": db_env.get('REDFIRE_MYSQL_DATABASE', env_config.get('REDFIRE_MYSQL_DATABASE', 'redfire_trading')),
            "username": db_env.get('REDFIRE_MYSQL_USER', env_config.get('REDFIRE_MYSQL_USER', 'redfire_app')),
            "password": "${REDFIRE_MYSQL_PASSWORD:redfire_app_2025}",
            "pool_size": 10,
            "max_overflow": 20,
            "echo": False
        }
        
        # InfluxDB时序数据库配置
        unified['databases']['timeseries'] = {
            "type": "influxdb",
            "host": env_config.get('INFLUXDB_HOST', 'localhost'),
            "port": int(env_config.get('INFLUXDB_PORT', '8086')),
            "org": env_config.get('INFLUXDB_ORG', 'redfire_org'),
            "bucket": env_config.get('INFLUXDB_BUCKET', 'redfire_bucket'),
            "token": "${INFLUXDB_TOKEN:redfire_influx_2025}",
            "username": env_config.get('INFLUXDB_USERNAME', 'redfire_admin'),
            "password": "${INFLUXDB_PASSWORD:redfire_influx_2025}"
        }
    
    def _merge_cache_config(self, unified: Dict[str, Any], existing: Dict[str, Any]):
        """合并缓存配置"""
        env_config = existing.get('environment', {})
        
        unified['cache'] = {
            "redis": {
                "host": env_config.get('REDIS_HOST', 'localhost'),
                "port": int(env_config.get('REDIS_PORT', '6379')),
                "db": int(env_config.get('REDIS_DB', '0')),
                "password": "${REDIS_PASSWORD:}",
                "timeout": 5,
                "max_connections": 10
            }
        }
    
    def _merge_security_config(self, unified: Dict[str, Any], existing: Dict[str, Any]):
        """合并安全配置"""
        env_config = existing.get('environment', {})
        
        unified['security'] = {
            "jwt_secret_key": "${JWT_SECRET_KEY:your_secret_key_change_in_production}",
            "jwt_algorithm": "HS256",
            "jwt_access_token_expire_minutes": 30,
            "jwt_refresh_token_expire_days": 7,
            "cors_origins": [
                "http://localhost:3000",
                "http://localhost:8080", 
                "http://127.0.0.1:3000",
                "http://127.0.0.1:8080"
            ],
            "cors_methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
            "cors_headers": ["*"],
            "cors_credentials": True
        }
    
    def _write_config_files(self, unified_config: Dict[str, Any]):
        """写入配置文件"""
        print("📝 写入配置文件...")
        
        # 写入基础配置
        base_config_file = self.output_dir / "base.yml"
        with open(base_config_file, 'w', encoding='utf-8') as f:
            yaml.dump(unified_config, f, default_flow_style=False, allow_unicode=True, sort_keys=False)
        print(f"  ✓ 基础配置: {base_config_file}")
        
        # 写入开发环境配置
        dev_config = {
            "extends": "base.yml",
            "global": {"debug": True},
            "logging": {"level": "DEBUG", "handlers": [{"type": "console"}]},
            "monitoring": {"enabled": False}
        }
        
        dev_config_file = self.output_dir / "development.yml"
        with open(dev_config_file, 'w', encoding='utf-8') as f:
            yaml.dump(dev_config, f, default_flow_style=False, allow_unicode=True)
        print(f"  ✓ 开发配置: {dev_config_file}")
        
        # 写入生产环境配置
        prod_config = {
            "extends": "base.yml",
            "global": {"debug": False},
            "logging": {"level": "INFO"},
            "monitoring": {"enabled": True}
        }
        
        prod_config_file = self.output_dir / "production.yml"
        with open(prod_config_file, 'w', encoding='utf-8') as f:
            yaml.dump(prod_config, f, default_flow_style=False, allow_unicode=True)
        print(f"  ✓ 生产配置: {prod_config_file}")
        
        # 创建本地配置模板
        local_template = {
            "# 本地开发覆盖配置": None,
            "# 此文件不会被提交到版本控制": None,
            "# 可以在此处覆盖任何配置项": None,
            "services": {
                "# 示例: 覆盖服务端口": None,
                "# user_service:": None,
                "#   port: 8101": None
            }
        }
        
        local_template_file = self.output_dir / "local.yml.template"
        with open(local_template_file, 'w', encoding='utf-8') as f:
            yaml.dump(local_template, f, default_flow_style=False, allow_unicode=True)
        print(f"  ✓ 本地配置模板: {local_template_file}")
    
    def _generate_migration_report(self, existing_configs: Dict[str, Any], unified_config: Dict[str, Any]):
        """生成迁移报告"""
        report_file = self.output_dir / "migration_report.md"
        
        with open(report_file, 'w', encoding='utf-8') as f:
            f.write("# RedFire 配置迁移报告\n\n")
            f.write(f"迁移时间: {self._get_current_time()}\n\n")
            
            f.write("## 原有配置源\n\n")
            for source, config in existing_configs.items():
                f.write(f"### {source}\n")
                if source == 'environment' or source == 'database_env':
                    f.write(f"- 环境变量数量: {len(config)}\n")
                    for key, value in list(config.items())[:5]:  # 只显示前5个
                        f.write(f"  - {key}={value}\n")
                    if len(config) > 5:
                        f.write(f"  - ... 还有 {len(config) - 5} 个变量\n")
                elif source == 'service_config':
                    ports = config.get('ports', {})
                    hosts = config.get('hosts', {})
                    f.write(f"- 端口配置: {len(ports)} 个\n")
                    f.write(f"- 主机配置: {len(hosts)} 个\n")
                f.write("\n")
            
            f.write("## 统一配置结果\n\n")
            services = unified_config.get('services', {})
            databases = unified_config.get('databases', {})
            
            f.write(f"- 服务数量: {len(services)}\n")
            f.write(f"- 数据库数量: {len(databases)}\n\n")
            
            f.write("### 服务端口映射\n\n")
            for service_name, service_config in services.items():
                status = "✅ 启用" if service_config['enabled'] else "⏸️ 禁用"
                f.write(f"- **{service_config['name']}** ({service_name}): {service_config['port']} {status}\n")
            
            f.write("\n### 数据库配置\n\n")
            for db_name, db_config in databases.items():
                f.write(f"- **{db_name}**: {db_config['type']} @ {db_config['host']}:{db_config['port']}\n")
            
            f.write("\n## 迁移建议\n\n")
            f.write("1. 验证所有服务端口配置是否正确\n")
            f.write("2. 检查数据库连接配置\n")
            f.write("3. 更新环境变量设置\n")
            f.write("4. 测试服务启动和连接\n")
            f.write("5. 逐步替换旧配置文件的引用\n")
        
        print(f"📋 迁移报告: {report_file}")
    
    def _get_current_time(self) -> str:
        """获取当前时间字符串"""
        from datetime import datetime
        return datetime.now().strftime("%Y-%m-%d %H:%M:%S")

if __name__ == "__main__":
    migrator = ConfigMigrator()
    migrator.migrate_all()
